<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class User extends Controller
{
    //
    public function __construct(){
    	$this->permission = new \App\model\login();
    	date_default_timezone_set("Asia/Shanghai");
    }

    public function login(Request $request)
    {
    	$post = $request->all();
    	if (!isset($post['account'])) {
    		$error['reason'] = 'There\'s no account for login';
    		return $error['code'] = 1;
    	}elseif (!isset($post['password'])) {
    		$error['reason'] = 'There\'s no password for login';
    		return $error['code'] = 1;
    	}else{
    		$selfPermission = $this->permission->login($post);
    		if ($selfPermission == 0) {
    			$resoult['code'] = 0;
    			$resoult['success'] = 0;
    		}else{
    			$resoult['code'] = 0;
    			$resoult['success'] = 1;
    		}
            $resoult = json_encode($resoult);
    		return $resoult;
    	}
    }

    public function auth(Request $request){
    	$post = $request->all();

    	$salt = substr($post['account'], 2, 1);
    	$post['password'] = password_hash($post['password'].$salt, PASSWORD_DEFAULT);
        if (count(DB::table('sots_user')->select('id')->where(['account' => $post['account']]))) {
            $resoult['code'] = 4;
            $resoult['success'] = 0;
            return $resoult;
        }
    	$success = DB::table('sots_user')->insert($post) ? 1 : 0;
    	if ($success) {
    		$resoult['code'] = 0;
    		$resoult['success'] = 1;
    	}else{
    		$resoult['code'] = 0;
    		$resoult['success'] = 0;
    	}
    	return $resoult;
    }
}
